package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.config.FieldDisposeConfig;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmGoods;
import com.taobao.top.schema.exception.TopSchemaException;
import com.taobao.top.schema.factory.SchemaReader;
import com.taobao.top.schema.factory.SchemaWriter;
import com.taobao.top.schema.field.*;
import com.taobao.top.schema.option.Option;
import com.taobao.top.schema.value.ComplexValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author：LXY
 * @DATE：2025-09-14 12:33
 * @Description：根据产品发布规则 发布产品
 */
@Component
@Slf4j
public class Jh50AddProductHandler implements PriorityHandler {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CallTaoApiService callTaoApiService;
    @Override
    public int getPriority() {
        return 50;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        JSONObject data = request.getData();
        Long cid = data.getLong("categoryId");
        String jhTmCategorySchema = data.getString("categorySchema");
        JhTmAccount jhTmAccount = data.getObject("tmAccount", JhTmAccount.class);
        try {
            Map<String, Field> stringFieldMap = null;
            try {
                stringFieldMap = SchemaReader.readXmlForMap(jhTmCategorySchema);
            } catch (TopSchemaException e) {
                log.error("解析提交产品schema失败", e);
                throw new RuntimeException("解析提交产品schema失败"+e);
            }
            JhTmGoods item = data.getObject("item", JhTmGoods.class);
            Map<String, String> categoryData = item.getJhCatProp();
            if (categoryData == null || categoryData.isEmpty()) {
                throw new RuntimeException("商品属性为空");
            }
            categoryData.put("货号", generateItemNumber(jhTmAccount.getJhId().toString()));
            List<String> mainImage = data.getObject("uploadMainPic", List.class);
            for (Map.Entry<String, Field> entry : stringFieldMap.entrySet()) {
                String k = entry.getKey();
                Field v = entry.getValue();
                String name = v.getName();
                if ("品牌".equals(name)) {
                    // todo 暂时没看到过一个店铺多个品牌场景，如果有后面再改
                    if (CollectionUtils.isEmpty(((SingleCheckField) v).getOptions())) {
                        continue;
                    }
                    Option option = ((SingleCheckField) v).getOptions().get(0);
                    ((SingleCheckField) v).setValue(option.getValue());
                    continue;
                }
                if ("产品图片".equals(name)) {
                    if (mainImage.size() <5) {
                        throw new RuntimeException("主图数量少于5张");
                    }
                    ComplexValue complexValue = new ComplexValue();
                    ((ComplexField) v).getFieldList().forEach(f -> {
                        // todo 后面需要添加实际的图片
                        String id = f.getId();
                        complexValue.setInputFieldValue(id, mainImage.get(Integer.parseInt(id.substring(id.length() - 1))));
                    });
                    ((ComplexField) v).setComplexValue(complexValue);
                }

                if (categoryData.containsKey(name) || FieldDisposeConfig.isRequiredFields(v)) {
                    switch (v.getType()) {
                        case SINGLECHECK://单选类型
                            FieldDisposeConfig.disposeSingleCheck((SingleCheckField) v, categoryData.get(name));
                            if ("-1".equals(((SingleCheckField) v).getValue().getValue())) {
                                Field targetField = stringFieldMap.get("in_" + k);
                                if (targetField instanceof InputField) {
                                    ((InputField) targetField).setValue(categoryData.get(name));
                                }
                            }
                            break;
                        case INPUT://文本输入类型
                            // 特殊处理带in 的，原key一般都是 single_check
                            if (k.startsWith("in_") && stringFieldMap.containsKey(k.substring(3))) {
                                break;
                            }
                            FieldDisposeConfig.disposeInput((InputField) v, categoryData.get(name));
                            break;
                        case MULTICHECK://多选类型
                            FieldDisposeConfig.disposeMultiCheck((MultiCheckField) v, categoryData.get(name));
                            break;
                        case MULTICOMPLEX://多复合类型
                            FieldDisposeConfig.disposeMultiComplex(v, categoryData);
                    }
                }
            }

            String addProductData = null;
            try {
                addProductData = SchemaWriter.writeParamXmlString(new ArrayList<>(stringFieldMap.values()));
            } catch (TopSchemaException e) {
                log.error("转换提交产品schema失败", e);
                throw new RuntimeException(e);
            }
            // 参数中 complex 的 complex-value 不认，需要进行替换
            addProductData = addProductData.replace("complex-value", "fields");
            JSONObject addProductSchema = callTaoApiService.addProduct(jhTmAccount, cid, addProductData);
            if (addProductSchema.containsKey("add_product_result")) {
                String str = addProductSchema.getString("add_product_result");
                Map result = null;
                try {
                    result = SchemaReader.readXmlForMap(str);
                } catch (TopSchemaException e) {
                    log.error("解析产品id失败", e);
                    throw new RuntimeException(e);
                }
                InputField productId = (InputField) result.get("product_id");
                data.put("productId", productId.getValue().getValue());
            } else {
                JSONObject errorResponse = addProductSchema.getJSONObject("error_response");
                // 提取sub_msg的值
                String subMsg = errorResponse.getString("sub_msg");
                // 产品服务异常，请稍后重试。已存在产品ID为:[8431280204] 的产品;
                if (subMsg.contains("已存在产品ID为")) {
                    String productId = subMsg.substring(subMsg.indexOf("[") + 1, subMsg.indexOf("]"));
                    data.put("productId", productId);
                }
            }
        }catch (Exception e){
            request.setErrorInfo("发布产品时发生异常:"+e.getMessage());
            throw new RuntimeException("发布产品时发生异常:"+e);
        }
        return true;
    }
    /**
     * 生成格式为 货号，暂定
     *
     * @param accountId 店铺id
     * @return 格式化后的字符串
     */
    private String generateItemNumber(String accountId) {
        Object index = redisCache.getCacheObject(accountId);
        if (null == index) {
            redisCache.setCacheObject(accountId, 1, 12, TimeUnit.HOURS);
        } else {
            index = (Integer) index + 1;
            redisCache.setCacheObject(accountId, index, 12, TimeUnit.HOURS);
        }

        // 获取当前日期并格式化为 yyyymmdd
        java.time.LocalDate today = java.time.LocalDate.now();
        String dateStr = today.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 拼接结果
        return String.format("%s%s%04d", dateStr, accountId.substring(accountId.length() - 4), index);
    }
}
